import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/details/box_details_page.dart';
import 'package:nft_shop/login/controller/user_controller.dart';
import 'package:nft_shop/login/page/login_page.dart';
import 'package:nft_shop/market/model/models.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/notice/website_del.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/sift/conteroller/sift_conteroller.dart';
import 'package:nft_shop/sift/page/sift_page.dart';
import 'package:nft_shop/util/other_utils.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_app_bar.dart';
import 'package:nft_shop/widgets/my_scroll_view.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../conteroller/box_controller.dart';
import 'Invitebox/Invite_box_page.dart';

class BoxPage extends StatefulWidget {
  @override
  State<BoxPage> createState() => _BoxPageState();
}

class _BoxPageState extends State<BoxPage>
    with
        SingleTickerProviderStateMixin,
        AutomaticKeepAliveClientMixin,
        RouteAware {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 20;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
    _status = value;
    setState(() {});
  }

  late List<Article> banners = [];

  @override
  bool get wantKeepAlive => true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteUtils.routeObserver
        .subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    RouteUtils.routeObserver.unsubscribe(this);
    super.dispose();
  }

//回到当前页面
  @override
  void didPopNext() {
    refresh();
    print("盲盒返回刷新了---");
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
  }

  //获取数据
  Future<List> loadData({int? pageNum}) async {
    return await ServiceRepository.goodsSpecialList(
        page: pageNum!, pageSize: pageSize, isHot: 0, type: 2);
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    getBanners();
    try {
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      status = LoadStatusType.empty;
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: ++currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  //轮播图
  void getBanners() async {
    try {
      banners = await ServiceRepository.fetchBanners(
        type: 3,
        jump_type: 1
      );
      // ignore: unnecessary_statements
      setState(() {});
    } catch (e, s) {}
  }

  @override
  Widget build(BuildContext context) {
    print("盲盒刷新--");
    return Scaffold(
        appBar: MyAppBar(
          centerTitle: "盲盒",
          isBack: false,
        ),
        body: SmartRefresher(
          controller: refreshController,
          header: WaterDropHeader(),
          footer: ClassicFooter(),
          onRefresh: refresh,
          onLoading: loadMore,
          enablePullUp: true,
          child: Column(
            children: [
              swiperView(),
              Expanded(
                child: _bulidGridView(),
              ),
            ],
          ),
        ));
  }

  ///置顶
  List<Widget> _sliverBuilder(BuildContext context) {
    return <Widget>[
      //头部
      SliverToBoxAdapter(
        child: Column(
          children: [
            Container(
                margin: EdgeInsets.symmetric(horizontal: 14),
                child: LoadAssetImage(
                  "box_top",
                )),
          ],
        ),
      ),
    ];
  }

  ///顶部操作Widget
  Widget topWidget() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "综合排序",
            style: TextStyle(
                fontSize: 14,
                fontFamily: Global.mySemiboldFont,
                color: Global.kTheme.textPrimary3),
          ),
          Text(
            "销量",
            style: TextStyle(
                fontSize: 14,
                fontFamily: Global.mySemiboldFont,
                color: Global.kTheme.textPrimary3),
          ),
          Text(
            "发布时间",
            style: TextStyle(
                fontSize: 14,
                fontFamily: Global.mySemiboldFont,
                color: Global.kTheme.textPrimary3),
          ),
          Text(
            "价格",
            style: TextStyle(
                fontSize: 14,
                fontFamily: Global.mySemiboldFont,
                color: Global.kTheme.textPrimary3),
          ),
        ],
      ),
    );
  }

  ///盲盒
  Widget _gridViewWidget() {
    return SmartRefresher(
      controller: refreshController,
      header: WaterDropHeader(),
      footer: ClassicFooter(),
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: _bulidGridView(),
    );
  }

  _bulidGridView() {
    if (status != LoadStatusType.success) {
      return StatusViews(status);
    }
    return GridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      physics: BouncingScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 15,
        mainAxisSpacing: 15,
        childAspectRatio: 167 / 230,
      ),
      //maxCrossAxisExtent
      itemBuilder: (context, index) {
        GoodsSpecialList model = list[index];
        return _itemWidget(model);
      },
      itemCount: list.length,
    );
  }

  //item
  Widget _itemWidget(GoodsSpecialList model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = itemWidth * 173 / 167;
    return InkWell(
      // onTap: () => Get.to(BoxDetailsPage(id:model.id!)),
      onTap: () {
        Utils.pushPage(
            context,
            BoxDetailsPage(
              id: model.id!,
              type: 3,
            ));
      },
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
                  )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: LoadImage(
                    model.thumb ?? "",
                    width: double.infinity,
                    fit: BoxFit.fitHeight,
                    height: itemHeight,
                  ),
                ),
                Positioned(
                    left: 9,
                    top: 8,
                    child: _objectState(model.is_will_status == 1
                        ? "正在预售"
                        : (model.saleCount == model.allCount
                            ? "发行结束"
                            : "正在发行"))),
                Positioned(
                  bottom: 5,
                  left: 5,
                  child: Row(
                    children: [
                      issueView("发行", model.allCount.toString()),
                      SizedBox(
                        width: 10,
                      )
                      // ,
                      // issueView("已售", model.saleCount.toString()),
                    ],
                  ),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          model.title ?? "",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontFamily: Global.mySemiboldFont,
                              fontSize: 14,
                              color: Global.kTheme.textPrimary4),
                        ),
                        SizedBox(
                          height: 2,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(9),
                              child: LoadImage(
                                model.portrait ?? "",
                                width: 18,
                                height: 18,
                                holderImg: "header_img",
                              ),
                            ),
                            SizedBox(
                              width: 4,
                            ),
                            Expanded(
                              child: Text(
                                model.nickname ?? "",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 12,
                                    color: Global.kTheme.textPrimary0,
                                    fontFamily: Global.mySemiboldFont),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  Text(
                    "¥${model.basePrice}",
                    style: TextStyle(
                        fontFamily: Global.myDINFont,
                        color: Global.kTheme.textPrimary0,
                        fontSize: 16),
                  ),
                  SizedBox(
                    width: 5,
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  ///盲盒状态
  Widget _objectState(String state) {
    Color color = Color(0xFF50E3C2);
    if (state == "发行结束") {
      color = Colors.red;
    } else if (state == "正在发行") {
      color = Color(0xFF50E3C2);
    } else if (state == "正在预售") {
      color = Color(0xFF50E3C2);
    }
    return Container(
        height: 24,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          color: Global.kTheme.colorBackground3.withAlpha(100),
        ),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 6,
              height: 6,
              decoration: BoxDecoration(
                  color: color, borderRadius: BorderRadius.circular(3)),
            ),
            SizedBox(width: 3),
            Text(
              state,
              style: TextStyle(
                  color: Global.kTheme.textPrimary5,
                  fontSize: 12,
                  fontFamily: Global.mySemiboldFont),
            ),
          ],
        ));
  }

  ///盲盒类型
  Widget _objectType(String state) {
    return Container(
      height: 17,
      decoration: BoxDecoration(
        color: Global.kTheme.colorBackground3,
      ),
      padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
      child: Text(
        state,
        style: TextStyle(
            color: Global.kTheme.textPrimary5,
            fontSize: 10,
            fontFamily: Global.mySemiboldFont),
      ),
    );
  }

  //数量
  Widget issueView(String left, String right) {
    return Row(
      children: [
        Container(
          color: Global.kTheme.colorBackground3,
          padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
          child: Text(
            left,
            style: TextStyle(
                fontSize: 10,
                color: Global.kTheme.textPrimary5,
                fontFamily: Global.mySemiboldFont),
          ),
        ),
        Container(
          color: Color(0xFFB6B6B6),
          padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
          child: Text(
            right,
            style: TextStyle(
                fontSize: 10,
                color: Global.kTheme.textPrimary5,
                fontFamily: Global.mySemiboldFont),
          ),
        ),
      ],
    );
  }

  ///轮播图
  Widget swiperView() {
    return GetBuilder<SiftConteroller>(
      id: SiftConteroller.bannersID,
      builder: (logic) {
        return Container(
          height: 138,
          child: Swiper(
            itemCount: banners.length,
            loop: false,
            autoplay: true,
            autoplayDelay: 5000,
            pagination: SwiperPagination(
                margin: EdgeInsets.only(bottom: 10),
                builder: CustomPaginationBuilder(
                  color: Colors.white.withOpacity(0.5),
                  activeColor: Colors.white,
                )),
            itemBuilder: (_, index) {
              Article model = banners[index];
              return Container(
                margin: EdgeInsets.symmetric(horizontal: 14),
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: BannerImage(model.thumb ?? "")),
              );
            },
            onTap: (index) {
              Article model = banners[index];
              if (model.jumpType == 1) {
                if (UserController.to.isLogin) {
                  //跳转类型
                  Get.to(InviteBoxPage(ID: model.jumpContent ?? ""));
                } else {
                  Get.to(LoginPage());
                }
              } else {
                if (ObjectUtil.isNotEmpty(model.jumpContent)) {
                  Get.to(WebsiteDel(
                      (ObjectUtil.isEmpty(model.title) ? "详情" : model.title!),
                      model.jumpContent!));
                }
              }
            },
          ),
        );
      },
    );
  }

  ///imageWidget
  Widget BannerImage(String url, {BoxFit? fit = BoxFit.fill}) {
    return CachedNetworkImage(
        imageUrl: url,
        placeholder: (context, url) =>
            Center(child: CupertinoActivityIndicator()),
        errorWidget: (context, url, error) => Icon(Icons.error),
        fit: fit);
  }
}
